package workpool

import (
	"sync"
)

var (
	JobQueue        chan Job
	workpoolRunning bool
	_mu             sync.Mutex
)

func PublishEvent(job Job) {
	JobQueue <- job
}

func InitJobQueue(jobQueueSize int) {
	JobQueue = make(chan Job, jobQueueSize)
}

type Dispatcher struct {
	pool       chan chan Job
	maxWorkers int
	workers    []Worker
}

func NewDispatcher(maxWorkers int) *Dispatcher {
	pool := make(chan chan Job, maxWorkers)
	workers := make([]Worker, 0, maxWorkers)
	return &Dispatcher{pool: pool, maxWorkers: maxWorkers, workers: workers}
}

// Run 启动任务分发器，启动 worker
func (d *Dispatcher) Run() {
	for i := 0; i < d.maxWorkers; i++ {
		worker := NewWorker(d.pool, i)
		d.workers = append(d.workers, worker)
		worker.Start()
	}
	go d.dispatch()
}

func (d *Dispatcher) Shutdown() {
	// 关闭接收队列
	close(JobQueue)
	for _, worker := range d.workers {
		worker.Shutdown()
	}
}

// dispatch 将 Job 分发给不同的 worker
func (d *Dispatcher) dispatch() {
	for {
		job := <-JobQueue
		go func(job Job) {
			jobChan := <-d.pool
			jobChan <- job
		}(job)
	}
}
